package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.common.article.ArticleConstants;
import com.heima.common.message.NewsUpOrDownConstants;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    AuthorService authorService;
    @Autowired
    ApArticleConfigService apArticleConfigService;
    @Autowired
    ApArticleContentService apArticleContentService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Value("${file.minio.readPath}")
    String readPath;
    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    GeneratePageService generatePageService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;



    /**
     * wmNews  查询
     * ap_article   ap_article_confg   ap_article_content  保存3表数据
     * wmNews  修改  9  article_id
     * @param newsId 文章id
     */
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 300000)
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 根据文章id 查询自媒体文章信息
        WmNews wmNews = getWmNews(newsId);
        // 2. 根据wmNews信息封装ApArticle对象
        ApArticle article = parseApArticle(wmNews);
        // 3. 保存或修改apArticle对象
        saveOrUpdateApArticle(article);
        // 4. 保存配置信息 和 内容信息
        saveConfigAndContent(article,wmNews);
        // 5. 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),article);
        // 6. 修改WmNews的状态，将状态改为 9 并设置关联的articleId
        updateWmNews(wmNews,article);
        // 7. MQ通知es索引库 更新文章索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,article.getId());
        log.info("成功发送 索引库更新消息    文章id: {}",article.getId());
    }

    /**
     * TODO:封装方法
     *      6.修改WmNews的状态
     * @param wmNews
     * @param article
     */
    private void updateWmNews(WmNews wmNews,ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程修改自媒体文章状态失败");
        }
    }

    /**
     * TODO:封装方法
     *      4. 保存配置信息 和 内容信息
     * @param article
     * @param wmNews
     */
    private void saveConfigAndContent(ApArticle article, WmNews wmNews) {
        // 1. 保存文章配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(article.getId());
        config.setIsComment(true);// 是否允许评论
        config.setIsForward(true);//// 是否允许 转发
        config.setIsDown(false);// 是否下架
        config.setIsDelete(false);// 是否删除
        apArticleConfigService.save(config);
        // 2. 保存文章内容信息
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(article.getId());
        content.setContent(wmNews.getContent());
        apArticleContentService.save(content);
    }

    /**
     * TODO:封装方法
     *      3. 保存或修改apArticle对象
     * @param article
     */
    private void saveOrUpdateApArticle(ApArticle article) {
        if(article.getId()==null){
            // 保存
            article.setViews(0);
            article.setLikes(0);
            article.setComment(0);
            article.setCollection(0);
            this.save(article);
        }else {
            // 删除关联的 文章配置信息  和  文章详情信息
            apArticleConfigService.remove(
                    Wrappers.<ApArticleConfig>lambdaQuery()
                            .eq(ApArticleConfig::getArticleId,article.getId())
            );
            apArticleContentService.remove(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId,article.getId())
            );
            // 修改
            this.updateById(article);
        }
    }


    /**
     * TODO:封装方法
     *      2.根据wmNews信息封装ApArticle对象
     * @param wmNews
     * @return
     */
    private ApArticle parseApArticle(WmNews wmNews) {
        // 1. 创建article ,将wmNews的同名属性拷贝进去
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews,article);
        // 2. 单独设置articleId字段
        article.setId(wmNews.getArticleId());
        // 3. 其它需要补充字段  flag  layout
        article.setLayout(wmNews.getType());
        article.setFlag((byte)0);
        // 4. 频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询频道信息失败");
        }
        AdChannel channel = channelResult.getData();
        article.setChannelName(channel.getName());
        // 5. 作者信息
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        article.setAuthorId(Long.valueOf(apAuthor.getId()));
        article.setAuthorName(apAuthor.getName());
        return article  ;
    }

    /**
     * TODO:封装方法
     *      1.根据文章id 查询自媒体文章信息
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        // 1. 根据id使用feign接口远程查询
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmNews wmNews = result.getData();
        // 2. 判断文章是否为null
        if (wmNews ==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        // 3. 判断文章的状态 必须是  4 或 8
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)&&!WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章的状态不是审核通过状态，发布文章失败");
        }
        return wmNews;
    }


    /**
     * 查询文章列表显示在app端
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        // 1. 校验参数
        Integer size = dto.getSize();
        if(size==null || size<=0){
            dto.setSize(10);
        }
        if(StringUtils.isBlank(dto.getTag())){
            // 推荐频道
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (dto.getMinBehotTime()==null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime()==null) {
            dto.setMaxBehotTime(new Date());
        }
        if (!ArticleConstants.LOADTYPE_LOAD_MORE.equals(loadtype)&&!ArticleConstants.LOADTYPE_LOAD_NEW.equals(loadtype)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        // 2. 调用mapper 查询文章
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle article : articleList) {
            String images = article.getImages();
            if (StringUtils.isNotBlank(images)){ // webSite + 相对路径.jpg,相对路径2.jpg,相对路径3.jpg
                images = Arrays.stream(images.split(","))
                        .map(url-> webSite + url)
                        .collect(Collectors.joining(","));
                article.setImages(images);
            }
            // 拼接静态页 访问前缀
            article.setStaticUrl(readPath + article.getStaticUrl());
        }
        // 3. 封装返回结果
        return ResponseResult.okResult(articleList);
    }

    @Override
    public ResponseResult loadFromCache(Short loadtype, ArticleHomeDTO dto) {
        // 1. 从redis中 查询指定频道的缓存数据
        String hotArticleJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        // 2. 判断如果缓存为空，从数据库中查询
        if (StringUtils.isBlank(hotArticleJson)){
            return load(loadtype,dto);
        }
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleJson, HotArticleVo.class);
        // 3. 如果有缓存返回缓存的热点文章列表数据
        for (HotArticleVo articleVo : hotArticleVoList) {
            //            添加图片的访问前缀   webSite + url1,url2,url3
            String images = articleVo.getImages();
            if(StringUtils.isNotBlank(images)){
                images = Arrays.stream(images.split(","))
                        .map(url -> webSite + url)
                        .collect(Collectors.joining(","));
                articleVo.setImages(images);
            }
            //            添加静态页的访问前缀
            articleVo.setStaticUrl(readPath + articleVo.getStaticUrl());
        }
        return ResponseResult.okResult(hotArticleVoList);
    }
}